// Created by carolsail

import { ENUM_AUDIO_CLIP, ENUM_UI_TYPE } from "../Enum";
import { StaticInstance } from './../StaticInstance';
import AudioManager from "../manager/AudioManager";
import SdkManager from "../manager/SdkManager";
import ToastManager from "../manager/ToastManager";
import DataManager from "../manager/DataManager";
import BaseLayer from "./Baselayer";
import { privacyChannel } from "../Script/privacyChannel";
import bh_toast from "../Script/bh_toast";
import { privacyChannelVivo } from "../Script/privacyChannelVivo";

const { ccclass, property } = cc._decorator;

@ccclass
export default class MenuLayer extends BaseLayer {
    btn_siderBar: cc.Node = null
    btn_desktop: cc.Node = null
    btnStart: cc.Node = null
    btnStartVS: cc.Node = null
    btnSetting: cc.Node = null
    btnGames: cc.Node = null
    btnShare: cc.Node = null
    btnRank: cc.Node = null
    btnSkin: cc.Node = null
    currentLevel: cc.Node = null
    challegeCurrentTime: cc.Node = null
    onlineReward: cc.Node = null
    powerButton: cc.Node = null
    btnChallenge: cc.Node = null
    timeElapsed = 0
    onLoad() {
        this.btn_siderBar = cc.find("btn_sidebar", this.node)
        this.btn_desktop = cc.find("btn_desktop", this.node)
        this.btnStart = cc.find('main/btn_start', this.node)
        this.btnChallenge = cc.find('main/btn_challenge', this.node)
        this.btnStartVS = cc.find('main/btn_start_vs', this.node)
        this.btnRank = cc.find('btn_rank', this.node)
        this.btnSkin = cc.find('btn_skin', this.node)
        this.btnSetting = cc.find('bottom/btn_setting', this.node)
        this.btnGames = cc.find('bottom/btn_games', this.node)
        this.btnShare = cc.find('bottom/btn_share', this.node)
        this.powerButton = cc.find("btn_power", this.node)
        this.btnChallenge.on('click', () => {
            this.onStartClick(true)
        }, this)
        this.btnStart.on('click', () => {
            this.onStartClick(false)
        }, this)
        this.btnStartVS.on('click', this.onStartVSClick, this)
        this.btnRank.on('click', this.onRankClick, this)
        this.btnSkin.on('click', this.onSkinClick, this)
        this.btnSetting.on('click', this.onSettingClick, this)
        this.btnGames.on('click', this.onGamesClick, this)
        this.btnShare.on('click', this.onShareClick, this)
        this.powerButton.on("click", this.onClickPower, this)
        this.btn_siderBar.on('click', () => {
            AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK)
            StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MENU, false)
            StaticInstance.uiManager.toggle(ENUM_UI_TYPE.CommonBarLayer)
        }, this)
        this.btn_desktop.on("click", () => {
            AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK)
            StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MENU, false)
            StaticInstance.uiManager.toggle(ENUM_UI_TYPE.Desktop)
        }, this)
        this.currentLevel = cc.find('main/btn_start/current_level/num', this.node)
        this.challegeCurrentTime = cc.find('main/btn_challenge/current_level/num', this.node)
        this.onlineReward = cc.find("onlineReward/onlineReward", this.node)
        this.onlineReward.on("click", this.onClickOnlineReward, this)
        if (!cc.sys.localStorage.getItem("onlineRewardTime")) { //从来没有领取过
            cc.sys.localStorage.setItem("onlineRewardTime", 1)
            cc.sys.localStorage.setItem("onlineTimeLeft", 120)
        }
        this.timeElapsed = 0
        this.onlineReward.parent.getChildByName("time").getComponent(cc.Label).string = this.formatTime(parseInt(cc.sys.localStorage.getItem("onlineTimeLeft") || '0'));
        let onlineTimeLeft = parseInt(cc.sys.localStorage.getItem("onlineTimeLeft") || '0');
        this.onlineReward.parent.getChildByName("time").getComponent(cc.Label).string = this.formatTime(onlineTimeLeft);
        switch (privacyChannel.channel) {
            case "oppo":
                this.onlineReward.parent.active = true
                cc.find("Canvas/UI/MenuLayer/title/ui_title_text1").active = true

                this.powerButton.active = false
                break
            case "oppo1":
                this.onlineReward.parent.active = true
                cc.find("Canvas/UI/MenuLayer/title/ui_title_text3").active = true

                this.powerButton.active = false
                break
            case "xm":
                this.onlineReward.parent.active = true
                cc.find("Canvas/UI/MenuLayer/title/ui_title_text1").active = true

                this.powerButton.active = false
                break
            case "vivo":
                (privacyChannel.getChannel() as privacyChannelVivo).hasShortcutInstalled((hasShortcut) => {
                    if (!hasShortcut) {
                        (privacyChannel.getChannel() as privacyChannelVivo).createShortcutButton();
                        //(privacyChannel.getChannel() as privacyChannelVivo).createShortcutButtonResistance()
                    }
                });

                this.onlineReward.parent.active = true
                cc.find("Canvas/UI/MenuLayer/title/ui_title_text1").active = true
                this.powerButton.active = false
                break
            case "vivo1":
                (privacyChannel.getChannel() as privacyChannelVivo).hasShortcutInstalled((hasShortcut) => {
                    if (!hasShortcut) {
                        (privacyChannel.getChannel() as privacyChannelVivo).createShortcutButton();
                        //(privacyChannel.getChannel() as privacyChannelVivo).createShortcutButtonResistance()
                    }
                });

                this.onlineReward.parent.active = true
                // cc.find("Canvas/UI/MenuLayer/title/ui_title_text3").active = true
                this.powerButton.active = false
                break
            case "xm":
                this.onlineReward.parent.active = true
                cc.find("Canvas/UI/MenuLayer/title/ui_title_text1").active = true
                this.powerButton.active = false
                break
            case "ks":
                this.onlineReward.parent.active = false
                cc.find("Canvas/UI/MenuLayer/title/ui_title_text2").active = true
                this.powerButton.active = true
                break
            default:
                this.onlineReward.parent.active = true
                cc.find("Canvas/UI/MenuLayer/title/ui_title_text1").active = true
                this.powerButton.active = false
                break
        }
        // this.schedule(() => {
        //     console.log("schedule");

        //     // 修正存储项的获取和更新
        //     let onlineTimeLeft = parseInt(cc.sys.localStorage.getItem("onlineTimeLeft") || '0');
        //     let onlineRewardTime = parseInt(cc.sys.localStorage.getItem("onlineRewardTime") || '0');

        //     // 更新剩余在线时间
        //     onlineTimeLeft -= 1;
        //     cc.sys.localStorage.setItem("onlineTimeLeft", onlineTimeLeft.toString());

        //     // 更新界面显示
        //     this.onlineReward.parent.getChildByName("time").getComponent(cc.Label).string = this.formatTime(onlineTimeLeft);

        //     // 检查是否可以领取奖励
        //     if (onlineRewardTime <= 0) {
        //         this.onlineReward.getChildByName("time").getComponent(cc.Label).string = "领取";
        //         this.onlineReward.getComponent(cc.Button).interactable = false;
        //     }
        // }, 1, cc.macro.REPEAT_FOREVER, 0);
        this.dealWithDesktopANdSideBar()
    }
    show(): void {
        let onlineTimeLeft = parseInt(cc.sys.localStorage.getItem("onlineTimeLeft") || '0');
        this.onlineReward.parent.getChildByName("time").getComponent(cc.Label).string = this.formatTime(onlineTimeLeft);
        this.dealWithDesktopANdSideBar()
        super.show()


    }
    hide() {
        super.hide()
        switch (privacyChannel.channel) {
            case "vivo":
            case "vivo1":
                (privacyChannel.getChannel() as privacyChannelVivo).hideButton()
                break
        }

    }

    dealWithDesktopANdSideBar() {
        switch (privacyChannel.channel) {
            case "ks":
                console.error("ks")
                if (cc.sys.localStorage.getItem("desktop") != 1) {
                    this.btn_desktop.active = true
                } else {
                    this.btn_desktop.active = false
                }
                if (cc.sys.localStorage.getItem("commonReward") == 1) {
                    this.btn_siderBar.active = false
                } else {
                    this.btn_siderBar.active = true
                }
                // try {
                //     ((privacyChannel.getChannel() as privacyChannelKS).checkSliderBarIsAvailable((flag) => {
                //         console.error("是否显示侧边栏", flag, flag == true, flag == false)
                //         this.siderBar.active = flag
                //     }))
                // } catch {
                //     // this.siderBar.active = true
                //     console.error("checkSliderBarIsAvailable 非快手环境")
                // }
                break
            default:
                this.btn_siderBar.active = false
                this.btn_desktop.active = false
                break
        }
    }
    update(dt: number) {
        // 累加每帧的时间
        this.timeElapsed += dt;

        // 每秒执行一次


        // 重置计时器
        this.timeElapsed = 0;

        // 修正存储项的获取和更新
        let onlineTimeLeft = parseInt(cc.sys.localStorage.getItem("onlineTimeLeft") || '0');


        // 检查是否可以领取奖励
        if (onlineTimeLeft <= 0) {
            this.onlineReward.parent.getChildByName("time").getComponent(cc.Label).string = "领取";
            this.onlineReward.getComponent(cc.Button).interactable = true;
            if (!this.onlineReward.getComponent(cc.Animation).getAnimationState("shake").isPlaying) {
                this.onlineReward.getComponent(cc.Animation).play()
            }
        } else {
            this.onlineReward.parent.getChildByName("time").getComponent(cc.Label).string = this.formatTime(onlineTimeLeft);
        }

    }


    formatTime(seconds: number): string {
        const minutes = Math.floor(seconds / 60); // 获取分钟数
        const remainingSeconds = seconds % 60; // 获取剩余秒数
        return `${minutes}：${remainingSeconds}`;
    }

    onDestroy() {
        this.btnStart.off('click', this.onStartClick, this)
        this.btnStartVS.off('click', this.onStartVSClick, this)
        this.btnRank.off('click', this.onRankClick, this)
        this.btnSkin.off('click', this.onSkinClick, this)
        this.btnSetting.off('click', this.onSettingClick, this)
        this.btnGames.off('click', this.onGamesClick, this)
        this.btnShare.off('click', this.onShareClick, this)
    }

    onEnable() {
        this.rendor()
        this.rendorPower()
        this.rendorPowerTimer()
        switch (privacyChannel.channel) {
            case "oppo":
            case "oppo1":
            case "vivo":
            case "vivo1":
            // this.node.getChildByName("btn_vivodesktop").active = true
            // this.node.getChildByName("btn_vivodesktop").on("click", () => {
            //     console.log("创建桌面")
            // }, this)
            case "xm":
                if (privacyChannel.getChannel().getCtrl("p1")) {
                    try {
                        privacyChannel.getChannel().showBanner()
                    } catch (e) {
                        console.error("p1控制", e)
                    }
                }
                if (privacyChannel.getChannel().getCtrl("p1")) {
                    this.schedule(() => {
                        try {
                            privacyChannel.getChannel().showBanner()
                        } catch (e) {
                            console.error("p1控制", e)
                        }

                    }, 5, cc.macro.REPEAT_FOREVER, 0)
                }

                console.error("ov 开始游戏的动画")
                let t1 = cc.tween(cc.find("main/btn_start", this.node)).to(0.7, { scale: 1.1 })
                let t2 = cc.tween(cc.find("main/btn_start", this.node)).to(0.7, { scale: 1 })
                cc.tween(cc.find("main/btn_start", this.node)).sequence(t1, t2).repeatForever().start()
                break
            case "ks":
                if (privacyChannel.getChannel().getCtrl("p4")) {
                    //StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MENU, false)
                    StaticInstance.uiManager.toggle(ENUM_UI_TYPE.LOGINREWARD)
                }
                break

        }
    }

    onDisable() { }

    rendor() {
        this.currentLevel.getComponent(cc.Label).string = `${DataManager.instance.level}关`
        this.challegeCurrentTime.getComponent(cc.Label).string = cc.sys.localStorage.getItem("challegeTime") ? cc.sys.localStorage.getItem("challegeTime") : "无成绩"
    }

    async onStartClick(Challenge = false) {
        AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK)
        switch (privacyChannel.channel) {
            case "oppo":
                if (DataManager.instance.power <= 0) {
                    ToastManager.instance.show('红心已用完, 请补充红心', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
                } else {
                    if (privacyChannel.getChannel().getCtrl("p13")) {
                        privacyChannel.getChannel().showVideo(() => {

                        })
                    }
                    DataManager.instance.stageModel = Challenge
                    DataManager.instance.power -= 1
                    DataManager.instance.save()
                    await StaticInstance.fadeManager.fadeIn()
                    StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MENU, false)
                    StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MAIN)
                    StaticInstance.gameManager.onGameStart()
                }
                break
            case "oppo1":
            case "vivo":
            case "vivo1":
            case "xm":
            case "mg":
                if (DataManager.instance.power <= 0) {
                    ToastManager.instance.show('红心已用完, 请补充红心', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
                } else {
                    DataManager.instance.stageModel = Challenge
                    DataManager.instance.power -= 1
                    DataManager.instance.save()
                    await StaticInstance.fadeManager.fadeIn()
                    StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MENU, false)
                    StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MAIN)
                    StaticInstance.gameManager.onGameStart()
                }
                break
            case "ks":
                console.error("checkTime", Date.now(), parseInt(cc.sys.localStorage.getItem("powerTime")) + 24 * 60 * 60 * 1000)
                if (Date.now() <= (parseInt(cc.sys.localStorage.getItem("powerTime")) + 24 * 60 * 60 * 1000)) {
                    console.log('目标时间是 24 小时内的时间');
                    await StaticInstance.fadeManager.fadeIn()
                    StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MENU, false)
                    StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MAIN)
                    StaticInstance.gameManager.onGameStart()
                } else {
                    console.log('目标时间超过 24 小时');
                    DataManager.instance.stageModel = Challenge
                    if (DataManager.instance.power - 5 < 0) {
                        ToastManager.instance.show('红心不够, 请补充红心', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
                    } else {
                        if (privacyChannel.getChannel().getCtrl("p8")) {

                            privacyChannel.getChannel().showVideo(async () => {
                            })
                        }
                        DataManager.instance.power -= 5
                        DataManager.instance.save()
                        await StaticInstance.fadeManager.fadeIn()
                        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MENU, false)
                        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MAIN)
                        StaticInstance.gameManager.onGameStart()


                    }
                }
                break

        }

    }
    onClickPower() {
        AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK)
        console.error("onClickPowers")
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MENU, false)
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.POWER)
    }
    onClickOnlineReward() {
        AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK)
        console.error("onClickOnlineReward")
        cc.sys.localStorage.setItem("onlineRewardTime", Number(cc.sys.localStorage.getItem("onlineRewardTime")) + 1)
        cc.sys.localStorage.setItem("onlineTimeLeft", 120 * cc.sys.localStorage.getItem("onlineRewardTime"))
        this.onlineReward.getComponent(cc.Button).interactable = false;
        let onlineTimeLeft = parseInt(cc.sys.localStorage.getItem("onlineTimeLeft") || '0');
        this.onlineReward.parent.getChildByName("time").getComponent(cc.Label).string = this.formatTime(onlineTimeLeft);
        DataManager.instance.power += parseInt(cc.sys.localStorage.getItem("onlineRewardTime") || '0') - 1;
        this.rendorPower()
        this.onlineReward.getComponent(cc.Animation).setCurrentTime(0)
        this.onlineReward.getComponent(cc.Animation).stop()
        cc.resources.load("privacy/bh_toast", cc.Prefab, (error, prefab: cc.Prefab) => {
            if (error) {
                console.error(error);
                return;
            }
            let node = cc.instantiate(prefab);
            node.getComponent(bh_toast).show("获得在线奖励：体力X" + (parseInt(cc.sys.localStorage.getItem("onlineRewardTime") || '0') - 1),
                cc.director.getScene().getChildByName('Canvas').getChildByName("UI"))
        })

    }
    onStartVSClick() {
        AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK)
        ToastManager.instance.show('待开放...', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
    }

    onSettingClick() {
        AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK)
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MENU, false)
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.SETTING)
    }
    onGamesClick() {
        AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK)
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MENU, false)
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MORE)
    }

    onShareClick() {
        AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK)
        if (SdkManager.instance.getPlatform()) {
            SdkManager.instance.activeShare()
        } else {
            ToastManager.instance.show('仅支持小游戏平台', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
        }
    }

    onRankClick() {
        AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK)
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MENU, false)
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.RANK)
    }

    onSkinClick() {
        AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK)
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MENU, false)
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.SKIN)
    }
}
